<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Hash;
use Log;
use Encore\Admin\Facades\Admin;
use App\Models\Project;
use App\Models\Cabinet;
use App\Models\DeviceType;
use App\Models\Device;
use App\Models\ProjectUser;
use App\Models\ProjectPlan;
use App\Models\xfProject;
use App\Models\Points;
use App\Models\Floors;
use App\Handlers\WeconHandler;
//20210322
class ProjectController extends Controller
{
    /** 项目列表
    *adminid
    **/
    public function Projectlist(Request $request){
            $info = $request->all();
            $role = Db::table('admin_role_users')->where(['user_id'=>$info['adminId']])->first();

            if($role->role_id==3||$role->role_id==4||$role->role_id==5||$role->role_id==6){ //用户
                $projectlist = ProjectUser::where('user_id',$info['adminId'])->pluck('projectId')->toArray();
                $list = Project::whereIn('projectId',$projectlist)->select('projectname as text','projectId as value')->get()->toArray();
                array_unshift($list,['text'=>'全部项目','value'=>0]);
                // $projectlist = ProjectUser::where('user_id',$info['adminId'])->select('projectId as value','projectname as text')->get()->toArray();
	            // $adminuser = Db::table('admin_users')->where(['id'=>$info['adminId']])->first();
	            // $user_id = isset($adminuser->pid)?$adminuser->pid:$adminuser->id;
                //获取项目列表
                // $projectlist = Project::where(['user_id'=>$user_id])->pluck('projectId')->toArray();
                $project = Project::whereIn('projectId',$projectlist)->get()->toArray();
                // $dtype = Device::whereIn('projectId',$projectlist)->where(['pid'=>'0'])->groupBy('device_type')->pluck('device_type')->toArray();
                // $typelist = DeviceType::whereIn('dtypeId',$dtype)->select('dtypeId','typename')->get()->toArray();
	            // $list = Db::table('xfy_project')->where(['user_id'=>$user_id])->groupBy('project_type')->get()->toArray();
	        }
	        if($role->role_id==1){ //维修人员
                $project = Project::get()->toArray();
                // $dtype = Device::groupBy('device_type')->where(['pid'=>'0'])->pluck('device_type')->toArray();
                // $typelist = DeviceType::whereIn('dtypeId',$dtype)->select('dtypeId','typename')->get()->toArray();
	            // $list = Project::groupBy('project_type')->get()->toArray();
                // echo $list->toSql();die;
	        }
            if($role->role_id==8){
                $project = xfProject::select('name as projectname','id as projectId','lng','lat')->get()->toArray();
                $list = xfProject::select('name as text','id as value')->get()->toArray();
                array_unshift($list,['text'=>'全部项目','value'=>0]);
            }
            if ($project) {
                $body['resultBody'] = $project;
                $body['resultList'] = $list;
                $body['resultCode'] = 1;
            }else{
                $body['resultMsg'] = '暂无数据';
                $body['resultCode'] = 0;
            }
	return $body;
    }
    public function myProject(Request $request){
        $info = $request->all();
        $projectlist = ProjectUser::where('user_id',$info['adminId'])->pluck('projectId')->toArray();
        $list = Project::whereIn('projectId',$projectlist)->get()->toArray();
        if ($list) {
                $body['resultBody'] = $list;
                $body['resultCode'] = 1;
            }else{
                $body['resultMsg'] = '暂无数据';
                $body['resultCode'] = 0;
            }
        return $body;
    }
    public function getRealProjectBox(Request $request){
        $info = $request->all();
        $projectlist = ProjectUser::where('user_id',$info['adminId'])->pluck('projectId')->toArray();
        $list = Cabinet::whereIn('project_id',$projectlist)->select('name as text','box_id as value')->where(['pid'=>0])->get()->toArray();
        array_unshift($list,['text'=>'请选择项目','value'=>0]);
        
        if ($list) {
            $body['resultList'] = $list;
            $body['resultCode'] = 1;
        }else{
            $body['resultMsg'] = '暂无数据';
            $body['resultCode'] = 0;
        }
	    return $body;
    }
    public function getRealProjectGroup(Request $request){
        $info = $request->all();
        $list = Cabinet::where(['box_id'=>$info['boxId']])->select('name as text','group_id as value')->where('pid','>','0')->get()->toArray();
        array_unshift($list,['text'=>'请选择设备','value'=>0]);
        
        if ($list) {
            $body['resultList'] = $list;
            $body['resultCode'] = 1;
        }else{
            $body['resultMsg'] = '暂无数据';
            $body['resultCode'] = 0;
        }
	    return $body;
    }
    public function getProject(Request $request){
        $info = $request->all();
        // $user_id = getAdminId($info['adminId']);
        $project = ProjectUser::where(['user_id'=>$info['adminId']])->pluck('projectId')->toArray();
        $res['project'] = Project::whereIn('projectId',$project)->get(['projectname','projectId'])->toArray();
        // print_r($res['project']);die;
        // $res['project'] = Project::where(['user_id'=>$user_id])->get(['projectname','projectId'])->toArray();
        // if(count($res['project'])>1){
        $arr = array('projectId'=>0,'projectname'=>'请选择');
        array_unshift($res['project'],$arr);
        // }
        $res['dtype'] = DeviceType::get(['typename','dtypeId'])->toArray();
        $arr1 = array('dtypeId'=>0,'typename'=>'请选择');
        array_unshift($res['dtype'],$arr1);
        return json_encode($res);
    }

    public function getPlane(Request $request){
        $param = $request->all();
        $plane = ProjectPlan::where(['project_id'=>$param['projectId']])->get(['name','id'])->toArray();
        $arr = array('id'=>0,'name'=>'请选择');
        array_unshift($plane,$arr);
        // print_r($plane);die;
        return json_encode($plane);
    }

    //新增项目 projectname user_id
    public function addProject(Request $request){
    	$info = $request->all();
    	$res = Db::table('xfy_project')->where(['projectname'=>$info['projectname']])->first();
    	if($res){
    	    $result['resultCode'] = 0;
    	    $result['resultMsg'] = '该设备已添加';
    		return $result;
    	}else{
    		unset($info['_url']);
    		$user = Db::table('admin_users')->where(['id'=>$info['user_id']])->first();
    		$info['companyId'] = $user['companyId'];
    		$info['created_at'] = date("Y-m-d H:i:s");
    		Db::table('xfy_project')->insert($info);
    		return 1;
    	}
    }
    //设备列表
    /**
      *  设备类型 device_type
       * 设备名称 devicename
       * 项目id projectid
    **/
    public function DeviceList(Request $request){
        $info = $request->all();
        $role = Db::table('admin_role_users')->where(['user_id'=>$info['adminId']])->first();
        // if(isset($info['type'])&&$info['type']!='undefined'){
        //     $where['xfy_device.device_type'] = $info['type']; //品牌 设备类型project_type1烟感 2应急柜 3维控
        //     //device_type1霍尼韦尔 2川大 3NB 4锁 5应急柜 6 维控 7 西门子 8 采集点 9红外摄像头 10开关
        // }
        // print_r($role);die;
        // $user_id = getAdminId($info['adminId']);
        if($role->role_id==8){
            $where = [];
            if(isset($info['devicename'])){
                $where[] = ['name','like','%'.$info['devicename'].'%'];
            }
            if($info['projectId']==0){
                $cabinet = Floors::get()->toArray();
            }else{
                $cabinet = Floors::where('project_id',$info['projectId'])->get()->toArray();
            }
        }else{
            $where['pid'] = 0;
            if(isset($info['devicename'])){
                $where[] = ['name','like','%'.$info['devicename'].'%'];
            }
            if($info['projectId']==0){
                $projectlist = ProjectUser::where(['user_id'=>$info['adminId']])->pluck('projectId')->toArray();
                $cabinet = Cabinet::whereIn('project_id',$projectlist)->where($where)->get()->toArray();
            }else{
                $where['project_id'] = $info['projectId'];
                $cabinet = Cabinet::where($where)->get()->toArray();
            }
            foreach($cabinet as $key => &$cval){
                $check = WeconHandler::getBoxStatus($cval['machine_code']);
                if ($check) {
                    $cval['status'] = 'online';
                } else {
                    $cval['status'] = 'offline';
                }
                if($cval['address']==''){
                    $cval['address'] = '暂无';
                }
                if($info['status']==1){
                    if(!$check){ unset($cabinet[$key]);}
                }
                if($info['status']==2){
                    if($check){ unset($cabinet[$key]);}
                }
            }
        }
        
        // $res['resultBody']['device'] = Cabinet::whereIn('xfy_device.projectId',$projectlist)->where($where)
        // ->join('xfy_project', 'xfy_project.projectId', '=', 'xfy_device.projectId')
        // ->select('xfy_device.*','xfy_project.projectname')
        // ->get()->toArray();
        $res['resultBody'] = $cabinet;
        if($res['resultBody']){
            $res['resultCode'] = 1;
        }else{
            $res['resultCode'] = 0;
            $res['resultMsg'] = '';
        }
        return $res;
    }

    //新增设备
    public  function addDevice(Request $request){
        $info = $request->all();
		$device = Db::table('xfy_device')->where(['cid'=>$info['cid']])->first();
		if($device){
			$res['resultCode'] = 0;
			$res['resultMsg'] = '该设备已添加过！';
			return json_encode($res);
		}
		// Cache::forget('authtoken');
		//区分霍尼或者川大IMEI
// 		$info['cid'] = $info['device_type']==2?substr($info['cid'],6,15):$info['cid'];
        // $info['device_type'] = 1;
		if($info['device_type']==1){
		// 	$add_res = $this->testadd($info['cid']);
		// }else{

            $add_res = $this->deviceAdd($info['cid'],$info['device_type']);
		}
		if(isset($add_res['error_code'])){ //添加失败
			$res['resultCode'] = 0;
			$res['resultMsg'] = $add_res['error_desc'];
		}else{
			$arr = explode(",", $info['picker']);
			$info['province'] = $arr[0];
			$info['city'] = $arr[1];
			$info['area'] = $arr[2];
			unset($info['picker']);
			unset($info['_url']);
			$info['created_at'] = date("Y-m-d H:i:s");
			$info['updated_at'] = date("Y-m-d H:i:s");
// 			$info['avatar'] = trim($info['avatar'],'"');
			$info['gatewayId'] = $add_res['deviceId'];
			$id = Db::table('xfy_device')->insertGetId($info);
			//区分是否未输入输出

			$res['resultCode'] = 1;
			$res['resultMsg'] = '添加成功';
		}
		return json_encode($res);
    }

    public function deviceAdd($imei,$device_type){// GDHS90BWNB
//     	if($device_type==4){ //微信锁
// 		    require '../vendor/iot_sdk/Test.php';
//             $t = new \Test();
//             $productKey = 'a1zQYVHQ92L';
//             $deviceName = $imei;
//             $result = $t->registDeviceTest($productKey, $deviceName);
//             return $res;
// 		}
		if (!Cache::has('authtoken')) { //鉴权
		    authentication();
		}
		if($device_type==1){ //霍尼
			$dtype = 'GDHS90BWNB';
			$manu = 'Hisense';
			$devicetype = 'Smoke';
		}
// 		elseif ($device_type==2) { //川大
// 			$dtype = 'NB20';
// 			$manu = 'Cdsoft';
// 			$devicetype = 'Smoke';
// 		}else{//NB
// 			$this->testadd($imei);
// 			$dtype = 'SM001'; //输入输出
// 			$manu = 'XBWLW';//厂家ID
// 			$devicetype = 'Switch';
// 		}

		// $dtype = $device_type==2?'NB20':'GDHS90BWNB';
		// $manu = $device_type==2?'Cdsoft':'Hisense';
		//添加设备
		//测试appId XDkLPjvjfEhkym1rjiz_TH0zvZsa 正式 86y97uYn78Try5i1zFdTLiErnX4a
		//正式 https://device.api.ct10649.com:8743 测试 https://develop.ct10649.com:8093
        // $url = 'https://device.api.ct10649.com:8743/iocm/app/reg/v1.1.0/deviceCredentials?appId=86y97uYn78Try5i1zFdTLiErnX4a';
        //app_key 测试 XDkLPjvjfEhkym1rjiz_TH0zvZsa 正式 86y97uYn78Try5i1zFdTLiErnX4a
        //  $url = 'https://device.api.ct10649.com:8743/iocm/app/reg/v1.1.0/deviceCredentials?appId=86y97uYn78Try5i1zFdTLiErnX4a';
        // $header = array('Content-Type:application/json','Authorization:Bearer 58a39127ea29403badd0ddc5c0154b02','app_key:86y97uYn78Try5i1zFdTLiErnX4a');
        // $data = '{"verifyCode":"869512030307544","nodeId":"869512030307544","deviceInfo":{"manufacturerId":"Hisense","manufacturerName":"Hisense","deviceType":"Smoke","model":"GDHS90BWNB","protocolType":"CoAP"}}';
        // $result = $this->postSsl($url,$data,$header);

        $url = 'https://device.api.ct10649.com:8743/iocm/app/reg/v1.1.0/deviceCredentials?appId=86y97uYn78Try5i1zFdTLiErnX4a';

        $header = array('Content-Type:application/json','Authorization:Bearer '.Cache::get('authtoken'),'app_key:86y97uYn78Try5i1zFdTLiErnX4a');
        $data = '{"verifyCode":"'.$imei.'","nodeId":"'.$imei.'","deviceInfo":{"manufacturerId":"'.$manu.'","manufacturerName":"'.$manu.'","deviceType":"'.$devicetype.'","model":"'.$dtype.'","protocolType":"CoAP"}}';
        $a = postSsl($url,$data,$header);
        // Log::info('A');
        // Log::info($a);
        $res = json_decode($a['return'],1);

        return $res;
	}

	public function  weikonglist(){
	    $body['resultBody']['device'] = Db::table('xfy_device')->where(['device_type'=>6])->get()->toArray();
	    $body['resultCode'] =1;
	    return $body;
	}
	public function getweikong(Request $request){
	    $info = $request->all();
	    $body['resultBody']['device'] = Db::table('xfy_device')->where(['pid'=>$info['deviceId']])->get()->toArray();
	    $body['resultCode'] = 1;
	    return $body;
	}

	public function weikongdetail(Request $request){
	    $info = $request->all();
	    $body['resultBody']['device'] = Db::table('xfy_device')->where(['pid'=>$info['deviceId']])->get()->toArray();
	    $body['resultCode'] = 1;
	    return $body;
	}

	public function getWeikongLog(Request $request){
	    $info = $request->all();
	    $body['resultBody'] = Db::table('xfy_weikong')->where(['gatewayId'=>$info['id']])->get()->toArray();
	    $body['resultCode'] = 1;
	    return $body;
	}
}